<?php

namespace app\api\services\admin\setting;

use app\api\common\service\BaseServices;
use app\api\dao\admin\setting\UploadDao;
use think\Exception;
use think\facade\Filesystem;

class UploadServices extends BaseServices
{
    public function __construct(UploadDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @param array $where
     * @param array $field
     * @param array $with
     *
     * @return array
     * @throws \ReflectionException
     */
    public function select(array $where, array $field = ['*'], array $with = []): array
    {
        $where = array_filter($where, function ($value) {
            return $value !== '' && $value !== null;
        });
        [$page, $limit] = $this->getPageValue();
        $list  = $this->dao->selectList($where, '*', $page, $limit, 'id DESC', [], true)->toArray();
        $count = $this->dao->count($where);
        return compact('list', 'count');
    }

    /**
     * delete
     *
     * @param $id
     *
     * @return bool
     * @throws \ReflectionException
     */
    public function delete($id): bool
    {
        [$page, $limit] = $this->getPageValue(false);
        $publicPath = public_path();
        $data       = $this->dao->selectList($id, '*', $page, $limit, '', [], true)->toArray();
        if (empty($data)) {
            throw new \Exception('文件不存在');
        }

        $this->dao->destroy($id['id_in']);

        foreach ($data as $value) {
            $url = $value['url'] ?? '';
            if (!empty($publicPath . $url)) {
                if (file_exists($publicPath . $url)) {
                    unlink($publicPath . $url);
                }
            }
        }
        return true;
    }

    /**
     * @param $file
     *
     * @return mixed
     * @throws \think\Exception
     */
    public function uploadFile($file): mixed
    {
        $request       = app()->request;
        $file          = current($request->file());
        $ext           = strtolower($file->extension());
        $relative_path = 'upload/files/' . date('Ym');
        $img_exts      = [
            'jpg',
            'jpeg',
            'png',
            'gif',
        ];
        if (in_array($ext, $img_exts)) {
            $relative_path = 'upload/image/' . date('Ym');
        }
        $category = $request->param('category', '0');
        $data             = $this->base($relative_path);
        $data['category'] = $category;
        return $this->dao->save($data);
    }

    /**
     * 获取上传数据
     *
     * @param $relative_dir
     *
     * @return array
     * @throws \think\Exception
     */
    protected function base($relative_dir): array
    {
        $request      = app()->request;
        $relative_dir = ltrim($relative_dir, '/');
        $file         = current($request->file());
        if (!$file || !$file->isValid()) {
            throw new Exception('未找到上传文件');
        }
        $ext               = strtolower($file->extension());
        $ext_forbidden_map = ['php', 'php3', 'php5', 'css', 'js', 'html', 'htm', 'asp', 'jsp'];
        if (in_array($ext, $ext_forbidden_map)) {
            throw new Exception('不支持该格式的文件上传');
        }
        $file_size = $file->getSize();
        $file_name = $file->getOriginalName();
        $mime_type = $file->getMime();
        // 判断是否为图片类型
        $image_with = $image_height = 0;
        if (str_contains($mime_type, 'image')) {
            // 获取图片宽度和高度
            $imageInfo    = getimagesize($file->getRealPath());
            $image_with   = $imageInfo[0]; // 宽度
            $image_height = $imageInfo[1]; // 高度
        }
        $fileName = Filesystem::disk('public')->putFile($relative_dir, $file, function () {
            return md5(uniqid());
        });
        return [
            'url'          => "/storage/" . $fileName,
            'name'         => $file_name,
            //            'realpath'     => $full_path,
            'admin_id'     => $request->AdminInfo['id'] ?? '',
            'file_size'    => $file_size,
            'mime_type'    => $mime_type,
            'image_width'  => $image_with,
            'image_height' => $image_height,
            'ext'          => $ext,
            'storage'      => 'public',
        ];
    }
}
